import {ScrollView, View, Text, Image, Input, Textarea} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui';
import 'taro-ui/dist/style/components/modal.scss';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import api from 'api';
import checkedImg from '@/assets/image/my/m_checked.png';
import checkImg from '@/assets/image/my/mq_check.png';
import mcheckboxImg from '@/assets/image/my/m_checkbox.png';
import mqcheckboxImg from '@/assets/image/my/mq_checkbox.png';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      isShow: false,
      type: 0, //0未填写1已填写
      show: false,
    };
  }

  async componentDidMount() {
    this.getAnswer();
  }

  componentDidShow() {}

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async getAnswer() {
    let {actions} = this.props;
    let questionDetail = Taro.getStorageSync('questionDetail');
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    // this.initjudge();
    let params = {
      userId: user?.id || '',
      id: questionDetail.id,
    };
    let result = await api.investigationController.findUserDetail(params);
    if (result.success) {
      this.setState({
        type: questionDetail.type,
      });
      actions.action.commonChange('main.question', result.data.questions);
    }
  }

  renderList(list) {
    let {main, actions} = this.props;
    let {question} = main;
    let {type} = this.state;
    let listView = [];
    if (list.length > 0) {
      list.map((item, index) => {
        listView.push(
          <View className="content" style={list.length - 1 == index && type == 0 ? {marginBottom: '160rpx'} : {}}>
            <View className="radius">
              <Text className="order">{index + 1 > 9 ? index + 1 : '0' + (index + 1)}</Text>
            </View>
            <View className="title">
              <Text className="titles">{item.questionName}</Text>
            </View>
            {item.questionType == 1 ? (
              <View className="checkbox">{this.checkList(item.options, index)}</View>
            ) : item.questionType == 2 ? (
              <View className="checkbox">{this.checkboxList(item.options, index)}</View>
            ) : (
              <View>
                {type == 0 ? (
                  <Textarea
                    placeholder="请写下您想说的建议……"
                    placeholderStyle="color:#999999;"
                    className="r_text"
                    maxlength={512}
                    onInput={(e) => {
                      let str = '',
                        obj = {optionContent: ''};
                      if (e.detail.value) {
                        str = e.detail.value.replace(
                          /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
                          '',
                        );
                      }
                      obj.optionContent = str;
                      question[index].answerList = obj;
                      actions.action.commonChange('main.question', JSON.parse(JSON.stringify(question)));
                    }}
                  />
                ) : (
                  <Textarea
                    placeholderStyle="color:#999999;"
                    className="r_text"
                    maxlength={512}
                    value={item.answerList[0].optionContent}
                    disabled
                  />
                )}
              </View>
            )}
          </View>,
        );
      });
    }
    setTimeout(() => {
      this.setState({
        show: true,
      });
    }, 500);
    return listView;
  }

  //单选
  checkList(list, key) {
    let {type} = this.state;
    let {main, actions} = this.props;
    let {question} = main;
    let listView = [];
    list.map((item, index) => {
      listView.push(
        <View className="single">
          {type == 0 ? (
            <View className="single1">
              <View className="single1" onClick={() => this.singleClick(key, true, index)}>
                {item.check ? (
                  <Image className="checkImg" mode="widthFix" src={checkedImg} />
                ) : (
                  <Image className="checkImg" mode="widthFix" src={checkImg} />
                )}
                <View>
                  <Text className="optionName">{item.optionName}</Text>
                </View>
              </View>
            </View>
          ) : (
            <View className="single1">
              <View>
                {question[key].answerList[0].optionContent == item.id ? (
                  <Image className="checkImg" mode="widthFix" src={checkedImg} />
                ) : (
                  <Image className="checkImg" mode="widthFix" src={checkImg} />
                )}
              </View>
              <View>
                <Text className="optionName">{item.optionName}</Text>
              </View>
            </View>
          )}
        </View>,
      );
    });
    // }
    return listView;
  }

  //多选
  checkboxList(list, key) {
    let {type} = this.state;
    let {main, actions} = this.props;
    let {question} = main;
    let listView = [];
    if (type == 0) {
      list.map((item, index) => {
        listView.push(
          <View className="single">
            <View className="single1">
              <View className="single1" onClick={() => this.multioClick(key, !item.check, index)}>
                {item.check == true ? (
                  <Image className="checkImg" mode="widthFix" src={mcheckboxImg} />
                ) : (
                  <Image className="checkImg" mode="widthFix" src={mqcheckboxImg} />
                )}
                <View>
                  <Text className="optionName">{item.optionName}</Text>
                </View>
              </View>
            </View>
          </View>,
        );
      });
    } else if (type == 1 && question[key].answerList[0].optionContent != '') {
      let ocList = question[key].answerList[0].optionContent.split(',');
      list.map((item, index) => {
        listView.push(
          <View className="single">
            <View className="single1">
              <View>
                {ocList.indexOf(item.id.toString()) != -1 ? (
                  <Image className="checkImg" mode="widthFix" src={mcheckboxImg} />
                ) : (
                  <Image className="checkImg" mode="widthFix" src={mqcheckboxImg} />
                )}
              </View>
              <View>
                <Text className="optionName">{item.optionName}</Text>
              </View>
            </View>
          </View>,
        );
      });
    }
    return listView;
  }

  //单选选择
  singleClick(key, type, index) {
    let {main, actions} = this.props;
    let {question} = main;
    let options = question[key].options;
    options.map((item, i) => {
      item.check = false;
    });
    options[index].check = type;
    let arr = [];
    arr.push(options[index].id);
    question[key].answerList = arr;
    actions.action.commonChange('main.question', JSON.parse(JSON.stringify(question)));
  }

  //多选选择
  multioClick(key, type, index) {
    let {main, actions} = this.props;
    let {question} = main;
    let options = question[key].options;
    options[index].check = type;
    let arr = [];
    options.map((item) => {
      if (item.check) {
        arr.push(item.id);
      }
    });
    question[key].answerList = arr;
    actions.action.commonChange('main.question', JSON.parse(JSON.stringify(question)));
  }

  // status：0待审核、1业主审核通过、2业主审核不通过、3物业审核通过、4物业审核不通过'
  // async initjudge() {
  //   let itemStr = Taro.getStorageSync('b2b-wechat@login')
  //   if (itemStr) {
  //     let userInfo = itemStr.user;
  //     if (userInfo.communityName) {
  //       switch (userInfo.status) {
  //         case 0:
  //           await Taro.showToast({
  //             title: '绑定房屋正在审核中',
  //             icon: 'none',
  //             duration: 2000,
  //           });
  //           break;
  //         case 1:
  //           await Taro.showToast({
  //             title: '绑定房屋正在审核中',
  //             icon: 'none',
  //             duration: 2000,
  //           });
  //           break;
  //         case 2:
  //           await Taro.showToast({
  //             title: '绑定房屋未通过审核，请联系业主',
  //             icon: 'none',
  //             duration: 2000,
  //           });
  //           break;
  //         case 3:
  //           this.setState({
  //             isShow: false,
  //           });
  //           break;
  //         case 4:
  //           await Taro.showToast({
  //             title: '绑定房屋未通过审核，请联系业主',
  //             icon: 'none',
  //             duration: 2000,
  //           });
  //           break;
  //         default:
  //           this.setState({
  //             isShow: true,
  //           });
  //           break;
  //       }
  //     } else {
  //       this.setState({
  //         isShow: true,
  //       });
  //     }
  //   }
  // }

  //提交
  async subMit() {
    let questionDetail = Taro.getStorageSync('questionDetail');
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    let {
      main: {question},
      actions: {action},
    } = this.props;
    let arr = [];
    for (let i = 0; i < question.length; i++) {
      let optionContent = '';
      if (question[i].questionType == 1) {
        if (question[i].answerList.length == 0) {
          Taro.showToast({
            title: '单选题第' + (i + 1) + '题还未选择!',
            icon: 'none',
            duration: 2000,
          });
          return false;
        }
        optionContent = question[i].answerList[0];
      } else if (question[i].questionType == 2) {
        if (question[i].answerList.length == 0) {
          Taro.showToast({
            title: '多选题第' + (i + 1) + '题还未选择!',
            icon: 'none',
            duration: 2000,
          });
          return false;
        }
        if (question[i].answerList.length == 1) {
          optionContent = question[i].answerList[0];
        }
        optionContent = question[i].answerList.join(',');
      } else {
        if (!(question[i].answerList.optionContent && question[i].answerList.optionContent != '')) {
          Taro.showToast({
            title: '简答题第' + (i + 1) + '题还未选择!',
            icon: 'none',
            duration: 2000,
          });
          return false;
        }
        optionContent = question[i].answerList.optionContent;
      }
      arr.push({
        userId: user?.id || '',
        investigationId: questionDetail.id,
        questionId: question[i].id,
        optionContent,
      });
    }
    let params = {
      answers: JSON.parse(JSON.stringify(arr)),
    };
    let result = await api.investigationController.addAnswer({params});
    if (result.success) {
      Taro.showToast({
        title: '提交成功!',
        icon: 'none',
        duration: 2000,
      });
      Taro.navigateBack({delta: 2});
    }
  }

  render() {
    let {isShow, type} = this.state;
    let {question} = this.props.main;
    let questionDetail = Taro.getStorageSync('questionDetail');
    return (
      <ScrollView className="packageARepair" scrollY style={{opacity: this.state.show ? 1 : 0}}>
        <View className="titleBox">
          <Text className="titleText">{questionDetail.investigationName}</Text>
        </View>
        <View className="decBox">
          <Text className="dec">&emsp;&emsp;{questionDetail.investigationDescription}</Text>
        </View>
        {this.renderList(question)}
        <View className="status"></View>
        {type == 0 && (
          <View className="bottom">
            <View className="btn_box">
              <Text
                className="btn-release"
                onClick={() => {
                  this.subMit();
                }}
              >
                提交问卷
              </Text>
            </View>
          </View>
        )}
        {/* {
          isShow &&
          <AtModal
            isOpened={isShow}
            title='温馨提示'
            cancelText='取消'
            confirmText='去绑定'
            onClose={() => {
              this.setState({
                isShow: false,
              });
            }}
            onCancel={() => {
              this.setState({
                isShow: false,
              });
            }}
            onConfirm={() => {
              this.setState({
                isShow: false,
              }, () => {
                Taro.navigateTo({
                  url: '/pages/package-A/house/add/index'
                })
              });
            }}
            content='绑定房屋后才能使用此功能，请先去绑定哦～'
          />
        } */}
      </ScrollView>
    );
  }
}
